package com.huawei.M01.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * 不含重复数字的全排列
 *
 * @author 111
 */
public class Permute {
    public List<List<Integer>> permute(int[] nums) {
        // 使用递归进行解决
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> resHelp = new ArrayList<>(nums.length);
        boolean[] used = new boolean[nums.length];
        dfs(nums, 0, used, resHelp, result);
        return result;
    }

    private void dfs(int[] nums, int index, boolean[] used, List<Integer> resHelp, List<List<Integer>> result) {
        // 递归头
        if (index == nums.length) {
            result.add(new ArrayList<>(resHelp));
            return;
        }

        // for 循环查找满足条件的排列
        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                resHelp.add(nums[i]);
                used[i] = true;
                dfs(nums, index + 1, used, resHelp, result);
                //回溯
                used[i] = false;
                resHelp.remove(resHelp.size() - 1);
            }
        }
    }
}
